var actorId = 0;
if (gUserLoginResult.userActors.indexOf("1") >= 0)
    actorId = 1;

var mOrgId;

$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_org/getOrg4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.actorId = actorId;
                d.orgId = gUserLoginResult.orgId;
            }
        },
        columns: [{
            data: "orgId",
            render: function (data, type, row, meta) {
                if (gUserLoginResult.userActors == 1 && row.orgId == gUserLoginResult.orgId)
                    return null;
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' class='orgCheckBox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: null,
            targets: 0
        }, {
            data: "orgType",
            render: function (data, type, row) {
                if (gUserLoginResult.userActors == 1 && row.orgId == gUserLoginResult.orgId) {
                    return "<td>系统单位</td>";
                } else if (data == 1)
                    return "<td>监管单位</td>";
                else
                    return "<td>维护单位</td>";
            }

        }, {
            data: "orgName"
        }, {
            data: "orgPerson"
        }, {
            data: "orgPersonMobile"
        }, {
            data: "orgMobile"
        }, {
            data: "orgState",
            render: function (data, type, row) {
                if (data == 0)
                    return "<button class='btn btn-default btn-xs btn-flat' >正常</button>";
                if (data == 1)
                    return "<button class='btn btn-danger btn-xs btn-flat' >停用</button>";
            }
        }, {
            data: "orgId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showMore(" + JSON.stringify(row) + ")'><i class='glyphicon glyphicon-plus'></i> 详情</button>";
            }
        }, {
            data: "orgId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                // var buttonInsert = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.addOrg()' title='添加'><i class='fa fa-plus-square'></i></button>";
                var buttonDeactivate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deactivateOrg(" + data + "," + row.orgState + ")' title='停启用'><i class='fa fa-asterisk'></i></button>";
                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.updateOrg(" + JSON.stringify(row) + ")' title='编辑'><i class='fa fa-edit'></i></button>";
                var buttonSetMainOrg = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showSetOrgFatherModal(" + data + ")' title='添加监管单位'><i class='fa fa-building'></i></button> " +
                    "<button class='btn btn-primary btn-xs btn-flat' onclick='$.addMenu(" + data + ")' title='添加权限'><i class='fa fa-lock'></i></button>";
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteOrg(" + data + ")' title='删除'><i class='fa  fa-times'></i></button>";
                var buttonOperation = "";
                // gInsert == 0 ? buttonOperation : buttonOperation += buttonInsert + " ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate + " ";
                if (!(gUserLoginResult.userActors == 1 && row.orgId == gUserLoginResult.orgId)) {
                    gDelete == 0 ? buttonOperation : buttonOperation += buttonDeactivate + " ";
                    gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete + " ";
                }
                if (gInsert == 1) {
                    row.orgType == 1 ? buttonOperation += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : buttonOperation += buttonSetMainOrg;
                }

                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addOrg()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateOrg()'><i class='fa fa-edit'></i> 编辑</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deactivateOrg(0,0)'><i class='fa fa-minus-square'></i> 停用</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            strToolBar += "</ul></div> <div class='input-group input-group-sm'><input type='text' class='form-control' name='searchText' placeholder='公司'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    if (gUpdate == 0 && gDelete == 0 && gInsert == 0) {
        var oTable = $('#mainDataTables').dataTable();
        oTable.fnSetColumnVis(0, false);//隐藏列
        oTable.fnSetColumnVis(9, false);
    }

});

// 搜索框查询操作
$.fn.searchDT = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchContext = $("input[name='searchText']").val();
    gMainDT.search(searchContext).draw();
};
// DT头部的复选按钮全选操作
$.checkChange = function () {
    var isChecked = $("#batch_check").prop('checked');
    $(".orgCheckBox").prop("checked", isChecked);
};

$.getTime = function () {
    $.changeTimeType = function (date) {
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        return date;
    };
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = $.changeTimeType(date.getMonth() + 1);
    var strDate = $.changeTimeType(date.getDate());
    var hour = $.changeTimeType(date.getHours());
    var minutes = $.changeTimeType(date.getMinutes());
    var seconds = $.changeTimeType(date.getSeconds());

    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + hour + seperator2 + minutes
        + seperator2 + seconds;
    return currentdate;
};

$('#mainDataTables tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = gMainDT.row(tr);
    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        row.child(format(row.data())).show();
        tr.addClass('shown');
    }
});

var isEdit;
$.fn.searchInfoInMapedDt = function () {
    var search = $("#delTool input[name='searchInfo']").val().replace(/'/g, '');
    mappedDT.search(search).draw();
};

$.fn.searchInfoInMappingDt = function () {
    var search = $("#addTool  input[name='searchInfo']").val().replace(/'/g, '');
    mappingDT.search(search).draw();
};

$.addMainOrg = function (mainOrgId, orgId) {
    $.ajax({
        url: "../rds_org/addMainOrg4OrgId",
        type: 'post',
        dataType: 'json',
        data: {
            "orgId": orgId,
            "mainOrgId": mainOrgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    if (msg.jsonData > 0) {
                        $.alert("数据操作成功", 1);
                        mappedDT.ajax.reload(null, false);
                        mappingDT.ajax.reload(null, false);
                    } else {
                        $.alert("数据操作失败", 2);
                    }
                } else {
                    $.alert("数据操作失败", 2);
                    $.clearModal($('#form-org'), $('#modal-org'));
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
                $.clearModal($('#form-org'), $('#modal-org'));
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
            $.clearModal($('#form-org'), $('#modal-org'));
        }
    })
};

$.deleteOrg = function (orgId) {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">是否要删除该公司</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_org/deleteOrgByOrgId",
                    type: 'post',
                    async: false,
                    data: {"orgId": orgId},
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                if (msg.jsonData > 0) {
                                    $.alert("操作成功", 1);
                                    gMainDT.ajax.reload(null, false);
                                }
                                else
                                    $.alert("操作失败", 2);
                            } else
                                $.alert("该公司存在绑定数据 删除失败", 2)
                        }
                    }
                })
            }
        }
    })
};

$.deleteMainOrg = function (mainOrgId, orgId) {
    $.ajax({
        url: "../rds_org/deleteMainOrgByIds",
        type: 'post',
        dataType: 'json',
        data: {
            "orgId": orgId,
            "mainOrgId": mainOrgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    if (msg.jsonData > 0) {
                        $.alert("数据操作成功", 1);
                        mappedDT.ajax.reload(null, false);
                        mappingDT.ajax.reload(null, false);
                    } else {
                        $.alert("数据操作失败", 2);
                    }
                } else {
                    $.alert("数据操作失败", 2);
                    $.clearModal($('#form-org'), $('#modal-org'));
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
                $.clearModal($('#form-org'), $('#modal-org'));
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
            $.clearModal($('#form-org'), $('#modal-org'));
        }
    })
};

$.showSetOrgFatherModal = function (orgId) {
    mappedDT = $("#MainOrgDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_org/getMainOrgIdAndNameByOrgId",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.orgId = orgId;
            }
        },
        columns: [{
            data: null
        }, {
            data: "orgName"
        }, {
            data: "orgId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteMainOrg(" + data + "," + orgId + ")' title='移除'><i class='fa fa-minus-square'></i></button>";
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#delTool.col-md-6'>r>t<'row'<'col-md-12'>>",
        initComplete: function () {
            $("#delTool").empty();
            /*var strToolBar = "<div class='input-group input-group-sm'><input type='text' class='form-control' name='searchInfo' placeholder='公司名称'>";
             strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchInfoInMapedDt()'><i class='fa fa-search'></i></button></span></div>";
             $("#delTool").append(strToolBar);
             $("#delTool input[name='searchInfo']").bind('keydown', function (event) {
             if (event.keyCode == "13") {
             $(this).searchInfoInMapedDt();
             }
             });*/
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    mappingDT = $("#CandidateMainOrgDt").DataTable({
        destroy: true,
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 10,
        // autoWidth: false,
        ajax: {
            url: "../rds_org/getCandidateMainOrgIdAndNameByOrgId",
            type: "POST",
            data: function (d) {
                d.search = $('#CandidateMainOrgDt').DataTable().search(this.value);
                d.orgId = orgId;
            }
        },
        columns: [{
            data: null
        }, {
            data: "orgName"
        }, {
            data: "orgId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.addMainOrg(" + data + "," + orgId + ")' title='添加'><i class='fa fa-plus-square'></i></button>";
            }
        }],
        language: {
            url: "zh_cn.json"
        },
        dom: "<'row'<'col-md-6'><'#addTool.col-md-6'>r>t<'row'<'col-md-12'p>>",
        initComplete: function () {
            $("#addTool").empty();
            var strToolBar = "<div class='input-group input-group-sm'><input type='text' class='form-control' name='searchInfo' placeholder='公司名称'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchInfoInMappingDt()'><i class='fa fa-search'></i></button></span></div>";
            $("#addTool").append(strToolBar);
            $("#addTool input[name='searchInfo']").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).searchInfoInMappingDt();
                }
            });
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
    $("#mainOrg-modal").modal('show');
};

$.cleanOrgModal = function () {
    $("#org_check").prop("checked", false);
    $(".orgCheckBox").prop("checked", false);
    $.clearModal($('#form-orgFather'), $('#modal-setOrgFather'));

};

$.addOrg = function () {
    isEdit = false;
    $("#orgType").val(0);
    $("#label-org").text("添加公司信息");
    $("#modal-org").modal({
        backdrop: 'static',
        keyboard: false,
        show: true,
    });
};
// 编辑公司信息
$.updateOrg = function (jsonData) {
    isEdit = true;
    if (gUserLoginResult.userActors == 1 && jsonData.orgId == gUserLoginResult.orgId)
        $("#orgTypeDiv").hide();
    else
        $("#orgTypeDiv").show();
    $("#orgType").val(jsonData.orgType);
    $("#OrgName").val(jsonData.orgName);
    $("#orgPerson").val(jsonData.orgPerson);
    $("#orgPersonMobile").val(jsonData.orgPersonMobile);
    $("#orgMobile").val(jsonData.orgMobile);
    $("#orgFax").val(jsonData.orgFax);
    $("#orgWeb").val(jsonData.orgWeb);
    $("#orgRemark").val(jsonData.orgRemark);
    $("#orgEmail").val(jsonData.orgEmail);
    $("#orgAddress").val(jsonData.orgAddress);
    $("#orgId").val(jsonData.orgId);
    $("#label-org").text("编辑公司信息");
    $("#modal-org").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });

};

// 添加处理
$('#form-org').bootstrapValidator({

    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        orgName: {
            validators: {
                stringLength: {
                    min: 1,
                    max: 80,
                    message: "字数限制80"
                },
                notEmpty: {message: '公司名称不能为空'},
                callback: {
                    message: '公司名称重复',
                    callback: function (value, validator) {
                        return $.checkName();
                    }
                }
            }
        },
        orgRemark: {
            validators: {
                stringLength: {
                    min: 0,
                    max: 100,
                    message: "字数限制100"
                }
            }
        },
        orgPerson: {
            validators: {
                stringLength: {
                    min: 1,
                    max: 20,
                    message: "字数限制20"
                },
                notEmpty: {message: '公司负责人不能为空'}
            }
        },
        orgPersonMobile: {
            validators: {
                stringLength: {
                    min: 1,
                    max: 20,
                    message: "字数限制20"
                },
                notEmpty: {message: '公司负责人电话不能为空'},
                regexp: {
                    regexp: /^[0-9/-]+$/,
                    message: '号码只能包含数字和中划线'
                }

            }
        },
        orgMobile: {
            validators: {
                stringLength: {
                    min: 1,
                    max: 20,
                    message: "字数限制20"
                },
                notEmpty: {message: '公司电话不能为空'},
                regexp: {
                    regexp: /^[0-9/-]+$/,
                    message: '号码只能包含数字和中划线'
                }

            }
        },

        orgFax: {
            validators: {
                stringLength: {
                    min: 0,
                    max: 20,
                    message: "字数限制20"
                },
                regexp: {
                    regexp: /^[0-9/-]+$/,
                    message: '号码只能包含数字和中划线'
                }

            }
        },
        orgEmail: {
            validators: {
                stringLength: {
                    min: 0,
                    max: 50,
                    message: "字数限制50"
                },
                emailAddress: {message: '邮箱地址不正确'}

            }
        },
        orgWeb: {
            validators: {
                stringLength: {
                    min: 0,
                    max: 80,
                    message: "字数限制80"
                }
            }
        },
        orgAddress: {
            validators: {
                stringLength: {
                    min: 0,
                    max: 50,
                    message: "字数限制50"
                }
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var $form = $(e.target);
    var mydata = $form.serialize();
    var urlAddress = "../rds_org/addOrg";
    if (isEdit)
        urlAddress = "../rds_org/updateOrgById";
    else
        mydata += "&orgCreateTime=" + $.getTime() + "";
    $.ajax({
        url: urlAddress,
        type: 'post',
        data: mydata,
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    if (msg.jsonData > 0) {
                        if ($("#orgType").val() == 0) {
                            $.clearModal($('#form-org'), $('#modal-org'));
                            bootbox.confirm({
                                buttons: {
                                    confirm: {
                                        label: '<i class="fa fa-check"></i> 确定',
                                        className: 'btn btn-primary btn-flat'
                                    },
                                    cancel: {
                                        label: '<i class="fa fa-close"></i> 取消',
                                        className: 'btn btn-warning btn-flat pull-left'
                                    }
                                },
                                message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">是否要选择监管单位</b>',
                                callback: function (result) {
                                    if (result) {
                                        $.showSetOrgFatherModal(msg.jsonData);
                                    }
                                }
                            });
                        } else {
                            $.alert("数据操作成功", 1);
                            $.clearModal($('#form-org'), $('#modal-org'));
                        }
                        gMainDT.ajax.reload(null, false);
                    } else {
                        $.alert("数据操作失败", 2);
                    }
                } else {
                    $.alert("数据操作失败", 2);
                    $.clearModal($('#form-org'), $('#modal-org'));
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
                $.clearModal($('#form-org'), $('#modal-org'));
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
            $.clearModal($('#form-org'), $('#modal-org'));
        }
    });

});

$.checkName = function () {
    var boolean = true;
    if (!isEdit) {
        $.ajax({
            url: "../rds_org/getCountByOrgName",
            type: "post",
            async: false,
            data: {"orgName": $("#OrgName").val()},
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.jsonData >= 1) {
                        boolean = false;
                    }
                    else boolean = true;
                }
            }
        })
    }
    return boolean;
};

//删除分组
$.deactivateOrg = function (orgIds, orgState) {
    var count = 1,
        str = "",
        data;
    if (orgIds == 0) {
        var count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            if (orgState == 0)
                $.alert("请选择要停用的单位", 2);
            else
                $.alert("请选择要启用的单位", 2);
            return;
        } else {
            orgIds = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                orgIds += $(this).val() + ",";
            });
            orgIds = orgIds.substring(0, orgIds.length - 1);
        }
    }
    if (orgState == 0) {
        str = '确定停用该' + count + '个公司吗?';
        data = {"orgIds": orgIds, "orgState": 0}
    }
    else {
        str = '确定启用该' + count + '个公司吗?';
        data = {"orgIds": orgIds, "orgState": 1};
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">' + str + '</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_org/deactivateOrgByIds",
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                if (msg.jsonData > 0) {
                                    $.alert("数据操作成功", 1);
                                    gMainDT.ajax.reload(null, false);
                                } else {
                                    $.alert("数据操作失败", 2);
                                }
                            } else {
                                $.alert("数据操作失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function (msg) {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};

$.showMore = function (jsonData) {
    $.ajax({
        url: "../rds_org/getOrgNameByOrgId",
        async: false,
        type: 'post',
        dataType: 'json',
        data: {"orgId": jsonData.orgId, "orgType": jsonData.orgType},
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var data = msg.jsonData;
                    if (jsonData.orgType == 1)
                        $("#t").html("<b>维护单位</b>");
                    else
                        $("#t").html("<b>监管单位</b>");
                    $("#t2").empty();
                    var mainorg = "";
                    for (var i = 0; i < data.length; i++) {
                        i == 0 ? mainorg += " " : mainorg += "/";
                        mainorg += "" + data[i];
                    }
                    $("#t2").val(mainorg);
                }
            }
        }
    });
    $("#email").val(jsonData.orgEmail);
    $("#web").val(jsonData.orgWeb);
    $("#address").val(jsonData.orgAddress);
    $("#remark").html(jsonData.orgRemark);

    $("#information-modal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

var menu = [];
$.getOrgMenu = function (orgId) {
    $.ajax({
        url: "../rds_org/getOrgMenu",
        async: false,
        type: 'post',
        dataType: 'json',
        data: {
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    menu = msg.jsonData.split(",");
                } else
                    $.alert('数据操作失败', 2);
            } else
                $.alert('系统错误，请联系管理员', 2);
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
};

$.addMenu = function (orgId) {
    mOrgId = orgId;
    $("#label-menu").text("权限选择");
    $("#modal-menu").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
    $.getOrgMenu(orgId);
    var data = [];
    data[0] = {"menuId": '1', "menuName": "标牌"};
    data[1] = {"menuId": '2', "menuName": "信号灯"};
    data[2] = {"menuId": '3', "menuName": "信号机"};
    data[3] = {"menuId": '4', "menuName": "太阳能产品"};
    data[4] = {"menuId": '5', "menuName": "限高杆"};
    data[5] = {"menuId": '6', "menuName": "标线"};
    data[6] = {"menuId": '7', "menuName": "护栏"};
    data[7] = {"menuId": '8', "menuName": "监控箱"};
    data[8] = {"menuId": '9', "menuName": "井盖"};
    data[9] = {"menuId": '10', "menuName": "报警器"};
    var zNodes = [];
    var mFlag;
    for (var i = 0; i < data.length; i++) {
        mFlag = false;
        $.each(menu, function (key, value) {
            if (data[i].menuId == value) {
                mFlag = true;
                return false;
            }
        });
        zNodes[i] = {
            "id": data[i].menuId,
            "name": data[i].menuName,
            checked: mFlag
        };
    }

    var setting = {
        check: {
            enable: true,
            radioType: "all"
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };

    var code;

    function setCheck() {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var type = {"Y": "ps", "N": "ps"};
        zTree.setting.check.chkboxType = type;
        showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
    }

    function showCode(str) {
        if (!code) code = $("#code");
        code.empty();
        code.append("<li>" + str + "</li>");
    }

    $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    setCheck();
    $("#py").bind("change", setCheck);
    $("#sy").bind("change", setCheck);
    $("#pn").bind("change", setCheck);
    $("#sn").bind("change", setCheck);

};

function getChoosed() {
    var menuIds = "";
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    // console.log(nodes.length);
    for (var i = 0; i < nodes.length; i++) {
        v += nodes[i].name + ",";
        menuIds += nodes[i].id + ",";
    }
    menuIds = menuIds.substring(0, menuIds.length - 1);
    // console.log(menuIds);
    $.ajax({
        url: "../rds_org/addMenu",
        type: 'post',
        dataType: 'json',
        data: {
            orgMenu: menuIds,
            orgId: mOrgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                $.alert("数据操作成功", 1)
                $("#modal-menu").modal("hide");
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}
